<template>
  <div class="clear-fix k-btn-wrap">
    <div
      id="linpeng-handwriter-wraper"
      class="fl num-ul"
      :style="cp_left"
    >
    </div>
    <ul
      class="fr sym-ul sym-pad"
      :style="cp_right"
    >
      <li
        v-for="(row, idx) in cp_board.large"
        :key="idx"
        class="k-row"
        :class="{['k-row-' + cp_board.large.length]: 1}"
      >
        <template v-for="(btn, i) in row">
          <span
            v-if="btn.expect === 'delete'"
            :key="i"
            class="k-btn"
            :class="['k-' + btn.type, 'k-btn-' + cp_board.large[0].length, {active: active === `r_${idx}_${i}`}]"
            @touchstart.stop="deleteStart($event, btn, `r_${idx}_${i}`)"
            @touchend.stop="pressUp($event, btn)"
            @mousedown.stop="deleteStart($event, btn, `r_${idx}_${i}`)"
            @mouseup.stop="pressUp($event, btn)"
            @click.stop="pressClick($event, btn)"
          ><span class="k-btn-bg" /></span>
          <span
            v-else
            :key="i"
            class="k-btn"
            :class="['k-' + btn.type, 'k-btn-' + cp_board.large[0].length, {active: active === `r_${idx}_${i}`, disable: disableBtn.indexOf(btn.expect) > -1}]"
            @touchstart.stop="active = `r_${idx}_${i}`"
            @touchend.stop="btnClick($event, btn)"
            @mousedown.stop="!mobile && (active = `r_${idx}_${i}`)"
            @mouseup.stop="btnClick($event, btn)"
          >{{ btn.view || btn.text }}</span>
        </template>
      </li>
    </ul>
    <span class="iconfont icon-sqrt2" />
  </div>
</template>

<script>
import { KeepPress } from './index';
import { browerEnv, $debounce } from './utils';
import Handwriter from './handWriterClass';

export default {
    name: 'TheHandWriter',
    props: {
        boardData: {
            type: Object,
            required: true,
        },
        payload: {
            type: Object,
            default () {
                return {};
            },
        },
        disableBtn: {
            type: Array,
            default: () => {
                return [];
            },
        },
        mobile: {
            type: Boolean,
            default: true,
        },
    },
    data () {
        let press = new KeepPress();
        return {
            pressDown: press.down(($event, data) => {
                this.$emit('keep-press', $event, data);
                this.active = '';
            }, 1000),
            pressUp: press.up((e, data, cls) => {
                if (this.mobile) {
                    let { type } = e || window.event;
                    if (type.match(/mouse/g)) {
                        return false;
                    }
                }
                this.active = '';
                this.$emit('btn-click', e, data);
            }),
            pressClick: press.click(($event, data) => {
                this.active = '';
                this.$emit('btn-click', $event, data);
            }),
            active: '',
            handWriter: null,
        };
    },
    computed: {
        cp_board () {
            let { ordinary, large, defaultSymbol } = this.boardData.keysText;
            // let symbols = this.boardData.symbols;
            let i = 0;
            let len = ordinary.length;
            let pattern = this.payload.pattern;
            // let sym = symbols[0].items ? symbols[0].items : symbols[0];
            let result = Object.entries(defaultSymbol).map(([k, v]) => {
                return Object.assign({}, v, { text: k });
            });
            // result = sym.filter(itm => !itm.type.includes('double')).slice(0, Object.keys(defaultSymbol).length),
            // eslint-disable-next-line no-unused-vars
            // let isTurn = sym.length > Object.keys(defaultSymbol).length || symbols.length > 1;
            if (pattern === 'js') {
                Object.assign(
                    result.find(s => s.text === '\\S*\\frac {\\S*} {\\S*}') || {},
                    {
                        view: '°(度)',
                        text: '°',
                        type: 'symbol',
                        expect: '',
                    }
                );
            }
            return {
                ordinary: ordinary.map((arr, idx) => {
                    let res = [...arr];
                    if (idx === len - 1) {
                        // res.unshift(isTurn ? {
                        //   text: '更多',
                        //   type: "symbol middle",
                        //   expect: "switch"
                        // } : result[i++]);
                        // res.splice(0, 1, result[i++]);
                        res.unshift(result[i++]);
                        res.splice(1, 0, result[i++]);
                        res.push(result[i++]);
                        res.push(result[result.length - 1]);
                    } else {
                        res.unshift(result[i++]);
                        res.push(result[i++]);
                    }
                    return res;
                }),
                large,
            };
        },

        cp_right () {
            return (
                this.cp_board.large && {
                    width: '20%',
                }
            );
        },
        cp_left () {
            return (
                this.cp_board.large && {
                    width: '80%',
                }
            );
        },
    },
    mounted () {
        if (!this.handWriter) {
            this.handWriter = new Handwriter({
                id: '#linpeng-handwriter-wraper',
                offset: {
                    top: 10,
                    left: 10,
                },
                wordCb: (words, pre) => {
                    console.log(words);
                    this.$emit('handWriterCb', words, pre);
                },
            }).init();
        }
        let self = this;
        this.handWriterInit = $debounce(function () {
            if (self.handWriter) {
                self.handWriter.init();
            }
        }, 500);
        window.addEventListener('resize', this.handWriterInit);
    },
    destroyed () {
        window.removeEventListener('resize', this.handWriterInit);
    },
    methods: {
        btnClick (e, data) {
            if (this.mobile) {
                let { type } = e || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            this.$emit('btn-click', e, data);
            this.active = '';
        },
        deleteStart ($event, btn, cls) {
            if (this.mobile) {
                let { type } = $event || window.event;
                if (type.match(/mouse/g)) {
                    return false;
                }
            }
            this.active = cls;
            this.pressDown($event, btn);
        },
    },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.num-ul,
.sym-pad {
  height: 100%;
  width: 100%;
  padding: 10px;
}

.k-btn-wrap {
  position: relative;
  background: #f5f7f8;
  padding: 0;
}

.k-btn-box {
  z-index: 0;
}
</style>
